<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace app\common\controller;

/**
 * 微信H5页面控制器的基础类
 * @package app\common\controller
 * User: liuhongbin
 * Date: 2021-06-14 16:28
 */

use app\common\model\wework\WeworkKfMsg;
use hiduoke\services\facade\WechatService as Ws;
use hiduoke\services\WorkWechatService;
use think\App;
use think\facade\Cache;
use think\facade\Log;

abstract class WorkWechatController extends BaseController
{
    protected $notLogin = ['*'];
    protected $notCheck = ['*'];

    protected $visit_type = "index";
    protected WeworkKfMsg $MsgModel;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->view->config([
            'layout_on'   => true,
            'layout_name' => 'work_wechat/layout/default'
        ]);
        $this->MsgModel = new WeworkKfMsg();
    }

    /**
     * 当前控制器路由
     * @param $controller
     * @param string $action
     * @param array $vars
     * @return string
     */
    public function url($controller, $action = 'index', $vars = [])
    {
        return $this->workWechatUrl($controller, $action, $vars);
    }


    /**
     * 防止取token重复
     * @param string $token
     * @return bool
     */
    public function checkKfToken($token)
    {
        $tokens = Cache::get('checkKfToken') ?? [];
        if (in_array($token, $tokens)) {
            return false;
        } else {
            if (count($tokens) > 100) {
                $tokens = [];
            }
            $tokens[] = $token;
            Cache::set('checkKfToken', $tokens);
            return true;
        }
    }

    public function dealWithKefuMsg($message, $plaid)
    {
        try {
            global $_DK;
            $_DK['plaid'] = $plaid;
            $work = new WorkWechatService();
            if (isset($message['Token']) && $this->checkKfToken($message['Token'])) {
                //获取一个上下文
                $last_cursor = $this->MsgModel->where(['plaid' => $plaid])->order('id', 'desc')->value('cursor');
                //通过上下文解析最新的消息
                $msg = $work->getLastMsg($message, $last_cursor ?? '');
                if ($msg['errcode'] == 0) {
                    //保存消息
                    $this->MsgModel->saveMsgForEvent($msg['msg_list'][0] ?? [], $msg['next_cursor']);
                    //触发事件
                    event("wework_kf_message", [
                        'message' => $message,
                        'msg'     => $msg,
                        'plaid'   => $plaid
                    ]);
                }
            }
        } catch (\Exception $e) {
            Log::error(['dealWithKefuMsg' => [$e->getMessage(), $e->getLine(), $e->getFile()]]);
        }
    }
}
